#ifndef     __MUTE_PLAYER_H
#define     __MUTE_PLAYER_H


#include "./de_mux.h"
#include "./video_decoder.h"
#include "../utils/sync.h"
#include "../../app.h"
#include <thread>
#include <QLabel>

class MutePlayer : public QObject {
    Q_OBJECT
public:
    MutePlayer(const QString &file_path, QLabel *win) :
        m_demux(file_path),
        m_decoder(m_demux.video_stream(), win->width(), win->height()),
        m_sync(m_decoder.time_base()),
        m_win(win)
    {
        
    }

    ~MutePlayer() {
        m_sync.exit();
        if (m_task.joinable()) {
            m_task.join();
        }
    }

    void play() {
        m_task = std::thread(&MutePlayer::play_task, this);
    }

signals:
    void complete();
    void success();
    void error();

private:
    void play_task() {

        try {
            do_play();
            emit success();
        } catch (...) {
            emit error();
        }
        emit complete();
    }

    void do_play() {
        Packet packet( av_packet_alloc() );
        m_sync.update();
        for (;;) {
            
            if (!m_demux.read_packet(packet.packet)) {
                return;
            }
            if (packet->stream_index == m_demux.video_index()) {
                if (!m_decoder.send_packet(packet.packet)) {
                    return;
                }
                for (;;) {
                    ImageWrap img;
                    if (!m_decoder.receive_image(img)) { 
                        break;
                    }
                    if (!m_sync.wait_video(img.pts)) {
                        throw FFmpegException("play exit");
                    }
                    run_on_ui([this, img = std::move(img)]() mutable {
                        m_win->setPixmap( QPixmap::fromImage( std::move(img.image) ) );
                    });
                }
            }
            packet.unref();
        }
    }

private:
    DeMux m_demux;
    QImageVideoDecoder m_decoder;
    MuteSync m_sync;
    std::thread m_task;
    QLabel *m_win;
};



#endif
